#include "csvfile.h"

csvfile::csvfile()
{
    list_mac_line.clear();
    list_mac_var.clear();
    list_mac_status.clear();
}

csvfile::~csvfile()
{
    csv_closefile();
    list_mac_line.clear();
    list_mac_var.clear();
    list_mac_status.clear();
}

int csvfile::csv_openfile(QString filename)
{
    csvfile_fd.setFileName(filename);
    
    //判断文件是否存在
    if(csvfile_fd.exists()){
         qDebug()<<"File is exists";
        csvfile_fd.open(QIODevice::ReadWrite);
        return 0;
    }else{
        qDebug()<<"file does not exist";
        return -1;
    }
    
}

void csvfile::csv_closefile()
{
    csvfile_fd.close();
}

QString csvfile::csv_read_line(int lines)
{
    QTextStream filedata(&csvfile_fd);
    filedata.seek(LINE_MAX_LEN*lines+LEN_NOP);
    return filedata.readLine();
    // return 0;
}

int csvfile::csv_readall()
{
    QStringList tmp_str;
    QTextStream filedata(&csvfile_fd);
    filedata.seek(0);

    list_mac_status.clear();
    list_mac_var.clear();
    list_mac_line.clear();

    list_mac_line = filedata.readAll().split('\n');
//qDebug()<< " read 1  === " << list_mac_line.count() << endl;

    if(list_mac_line.count()>0)
        for(int i=0;i< list_mac_line.count();i++)
        {
            tmp_str = list_mac_line[i].split(',');
            //qDebug()<< " read 12  === " << list_mac_line.count() << endl;
            if(tmp_str.count()>=3)
            {
                list_mac_var.append(tmp_str[1].toUpper());
                // QString t=tmp_str[2].split('\r',QString::SkipEmptyParts)[0];
                QString t=tmp_str[2].mid(0,1);
                //qDebug()<< " read line mac  === " << list_mac_var << endl;
                list_mac_status.append(t);
            }
        }

    return 0;
}

int csvfile::list_find_mac(QString strtmp)
{
    int index = list_mac_var.indexOf(strtmp);
    return index;
}

int csvfile::csv_update_line(int lines,QString strdata)
{
    // csv_openfile();
    QTextStream filedata(&csvfile_fd);
    // filedata.reset();
    filedata.seek(0);
    
    // read data
    QString readdata=filedata.readLine();
    int seekt_index= (LINE_MAX_LEN+LEN_NOP)*(lines-1);

    filedata.seek(seekt_index+1);
    filedata<<strdata;
    
    /*checek write*/


    return 0;
}
